#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/init.h>
#include <linux/fs.h>
#include <linux/delay.h>
#include <linux/bitrev.h>
#include <linux/mutex.h>
#include <linux/uaccess.h>
#include <linux/io.h>
#include <linux/pci.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/file.h>
#include <linux/blkdev.h>
#include <linux/poll.h>
#include <linux/cdev.h>
#include <linux/jiffies.h>
#include <linux/percpu.h>
#include <linux/uio.h>
#include <linux/idr.h>
#include <linux/bsg.h>
#include <linux/slab.h>

#include<linux/of.h>
#include<linux/of_gpio.h>
#include<linux/gpio.h>
#include <linux/spinlock.h>
#include <linux/of_irq.h>
#include <linux/interrupt.h>
#include <linux/irq.h>

#define key_NAME "mykey"
#define key_NUM 1

#define CLOSE_CMD _IO(0x02,1)
#define OPEN_CMD _IO(0x02,2)
#define MODIFY_CMD _IO(0x02,3)


struct mykey
{
    dev_t devid;
    int major;
    int minor;
    struct cdev cdev;
    struct class *class;
    struct  device *device;
    struct device_node *node;
    int key_gpio;
    struct mutex lock;
    unsigned long flag;
    spinlock_t lock_spin; 
    unsigned int interrupt_id;

    int keyValue;
    int status;

    unsigned long expires; 
    struct timer_list timer;

    struct work_struct work;

    wait_queue_head_t queue_h;
};
struct myled
{
    int led_gpio;
    struct device_node* node;
};

static struct myled led;
static  struct mykey key;

static int key_open (struct inode * node, struct file * file)
{
    mutex_lock(&key.lock);
    return 0;
}
static int key_release (struct inode *node, struct file *file)
{
    mutex_unlock(&key.lock);
    return 0;
}
static ssize_t key_read (struct file *file, char __user *buff, size_t count, loff_t *loff)
{
    char value;

    // wait_event_interruptible(key.queue_h,key.status);
    DECLARE_WAITQUEUE(wait,current);

    spin_lock_irqsave(&key.lock_spin,key.flag);
    if(key.status==0)
    {
        add_wait_queue(&key.queue_h,&wait);//线程安全
        set_current_state(TASK_INTERRUPTIBLE);
        spin_unlock_irqrestore(&key.lock_spin,key.flag);
        
        schedule();
        if (signal_pending(current)) {
            spin_lock_irqsave(&key.lock_spin,key.flag);
			remove_wait_queue(&key.queue_h,&wait);
            set_current_state(TASK_RUNNING);
            spin_unlock_irqrestore(&key.lock_spin,key.flag);
            printk("task interrupt\r\n");
            return -1;
        }
    }
    spin_lock_irqsave(&key.lock_spin,key.flag);
    remove_wait_queue(&key.queue_h,&wait);
    set_current_state(TASK_RUNNING);
    value = key.keyValue;
    spin_unlock_irqrestore(&key.lock_spin,key.flag);

    if(copy_to_user(buff,&value,sizeof(value)))
    {
        printk("copy error!\r\n");
        return -1;
    }
    spin_lock_irqsave(&key.lock_spin,key.flag);
    key.status = 0;
    spin_unlock_irqrestore(&key.lock_spin,key.flag);

    return sizeof(value);
}

static void timer_function(unsigned long arg)
{
    static int status = 0;
    spin_lock_irqsave(&key.lock_spin,key.flag);
    
    if(gpio_get_value(key.key_gpio)==1)
    {
        status = !status;
        key.status = 1;
        key.keyValue=status;
    }
    if(key.status) wake_up(&key.queue_h);
    gpio_set_value(led.led_gpio,status);


    spin_unlock_irqrestore(&key.lock_spin,key.flag);

    return;
}
static void timer_in(void)
{
    key.timer.function = timer_function;
    key.expires =20;
    key.timer.expires = jiffies+msecs_to_jiffies(key.expires);
    key.timer.data = (unsigned long)&(key);
}


static void key_work_func_t(struct work_struct *work)
{
    struct mykey *Kkey = container_of(&key.work, struct mykey,work);
    mod_timer(&Kkey->timer,Kkey->timer.expires);//再用add就找个地锄吧。。
}



static long key_unlocked_ioctl (struct file *file, unsigned int cmd, unsigned long arg)
{
    switch (cmd)
    {
    case CLOSE_CMD:
        spin_lock_irqsave(&key.lock_spin,key.flag);
        del_timer_sync(&key.timer);
        spin_unlock_irqrestore(&key.lock_spin,key.flag);
        break;
    case OPEN_CMD:
        spin_lock_irqsave(&key.lock_spin,key.flag);
        timer_in();
        mod_timer(&key.timer,key.timer.expires );
        spin_unlock_irqrestore(&key.lock_spin,key.flag);
        break;
    case MODIFY_CMD:
        spin_lock_irqsave(&key.lock_spin,key.flag);
        key.expires = arg;
        spin_unlock_irqrestore(&key.lock_spin,key.flag);
        break;
    default:
        break;
    }
    return 0;
}

static  const struct file_operations fops = {
    .read = key_read,
    .open = key_open,
    .owner =THIS_MODULE,
    .release = key_release,
    .unlocked_ioctl = key_unlocked_ioctl,
};
//想要按键消抖，中断里触发定时器，定时器里读取按键值
static irqreturn_t key_irq_handler(int irq, void * dev)
{
    timer_in();
    schedule_work(&key.work);
    return 0;
}

static int led_init(void)
{
    int ret = 0;
    led.node = of_find_node_by_path("/gpioLED");
    if(IS_ERR(led.node))
    {
        printk("not find led node\r\n");
        goto error__;
    }
    led.led_gpio = of_get_named_gpio(led.node,"led-gpio-r",0);
    if(led.led_gpio<0)
    {
        printk("not find led gpio\r\n");
        goto error__;
    }
    ret = gpio_request(led.led_gpio,"gpioLED");
    if(ret)
    {
        printk("gpio_request error!\r\n");
        goto error__;
    }
    gpio_direction_output(led.led_gpio,0);

    return 0;

error__:
    return -1;
}
 
static int __init mykey_init(void)
{
    int ret = 0;
    if(key.major)
    {
        key.devid = MKDEV(key.major,key.minor);
        ret = register_chrdev_region(key.devid,key_NUM,key_NAME);
    }
    else
    {
        ret = alloc_chrdev_region(&key.devid,0,key_NUM,key_NAME);
    }
    if(ret< 0)
    {
        printk("register chrdev id error!\r\n");
        goto error__;
    }

    cdev_init(&key.cdev,&fops);
    ret = cdev_add(&key.cdev,key.devid,key_NUM);
    if(ret<0)
    {
        printk("cdev add error!\r\n");
        goto error_register_chrdev;
    }

    key.class = class_create(THIS_MODULE,key_NAME);
    if(IS_ERR(key.class))
    {
        printk("class creat failed!\r\n");
        goto error_cdev_add;
    }
    key.device = device_create(key.class,NULL,key.devid,NULL,key_NAME);
     if(IS_ERR(key.device))
    {
        printk("device creat failed!\r\n");
        goto error_class;
    }

    key.node = of_find_node_by_path("/key");
    if(IS_ERR(key.node))
    {
        printk("not find key node!\r\n");
        goto error_device;
    }
    key.key_gpio = of_get_named_gpio(key.node,"key_gpio",0);
    if(key.key_gpio<0)
    {
        printk("not find key gpio!\r\n");
        goto error_device;
    }

    ret = gpio_request(key.key_gpio,key_NAME);
    if(ret)
    {
        printk("request gpio error!\r\n");
        goto error_device;
    }

    gpio_direction_input(key.key_gpio);
    mutex_init(&key.lock);

    key.interrupt_id =  irq_of_parse_and_map(key.node,0);
    if(key.interrupt_id<0)
    {
        printk("not find interrupt id\r\n!");
        goto error_gpio_request;
    }
    ret = request_irq(key.interrupt_id, key_irq_handler, IRQF_TRIGGER_RISING|IRQF_TRIGGER_FALLING,key_NAME, &key);
    if(ret)
    {
        printk("request irq id is error!\r\n");
        goto error_gpio_request;
    }

    ret = led_init();
    if(ret<0)
        goto error_request_irq;

    init_timer(&key.timer);

    spin_lock_init(&key.lock_spin);

    INIT_WORK(&key.work,key_work_func_t);

    init_waitqueue_head(&key.queue_h);

    return 0;

error_request_irq://释放到request_irq为止申请过的所有资源
    free_irq(key.interrupt_id,&key);
error_gpio_request://释放到gpio_request为止申请过的所有资源
    gpio_free(key.key_gpio);
error_device:
    device_destroy(key.class,key.devid);
error_class:
    class_destroy(key.class);
error_cdev_add:
    cdev_del(&key.cdev);
error_register_chrdev:
    unregister_chrdev_region(key.devid,key_NUM);
error__:
    return -1;
}
static void __exit mykey_exit(void)
{
    free_irq(key.interrupt_id,&key);
    gpio_free(key.key_gpio);
    gpio_free(led.led_gpio);
    device_destroy(key.class,key.devid);
    class_destroy(key.class);
    cdev_del(&key.cdev);
    unregister_chrdev_region(key.devid,key_NUM);
    del_timer_sync(&key.timer);
}
module_init(mykey_init);
module_exit(mykey_exit);
MODULE_ALIAS("xiao");
MODULE_LICENSE("GPL");
